//
//  SetView.m
//  夺宝吧
//
//  Created by xiaocai on 15/7/20.
//  Copyright (c) 2015年 FangYuan. All rights reserved.
//

#import "SetView.h"
#import "VPImageCropperViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "AFNetworking.h"
#import "SexInPutView.h"
#import "AFHTTPSessionManager.h"
#import "NameInPutView.h"
#import "AgeInPutView.h"
#define ORIGINAL_MAX_WIDTH 640.0f
#define POST_IMG_URL @"/api/ApiUser/uploadAvatar"
#define EDIT_INFO_URL @"/api/ApiUser/editUserProfile"
@interface SetView ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIActionSheetDelegate, VPImageCropperDelegate>

{
    __weak IBOutlet UIImageView *img;
    __weak IBOutlet UIButton *nameBtn;
    __weak IBOutlet UILabel *idLab;
    __weak IBOutlet UILabel *phoneLab;
    __weak IBOutlet UIButton *sexBtn;
    __weak IBOutlet UIButton *ageBtn;
    __weak IBOutlet UIButton *ensureBtn;
    
    
    
}

@property (nonatomic , strong) NSString *selectedImageStr;

@end
@implementation SetView
- (void)awakeFromNib
{
    img.frame = CGRectMake(img.frame.origin.x-(AUTOX-1)*img.frame.size.width, img.frame.origin.y, img.frame.size.width*AUTOY, img.frame.size.height*AUTOY);
    img.layer.masksToBounds = YES;
    img.layer.cornerRadius = img.frame.size.width/2;
    img.layer.borderWidth = 2;
    img.layer.borderColor = [UIColor lightGrayColor].CGColor;
    ensureBtn.layer.cornerRadius = 2;
    ensureBtn.layer.masksToBounds = YES;
    ensureBtn.backgroundColor = QBB_RED_COLOR;
    //获取信息
    UserInfo *user = [[UserInfo alloc]init];
    [img sd_setImageWithURL:[NSURL URLWithString:user.user_header_img_path] placeholderImage:[UIImage imageNamed:@"icon_login_head"]];
    idLab.text = user.user_uid;
    [nameBtn setTitle:user.user_name forState:UIControlStateNormal];
    phoneLab.text = user.user_phone;
    [sexBtn setTitle:user.user_sex forState:UIControlStateNormal];
    [ageBtn setTitle:user.user_age forState:UIControlStateNormal];
    
    
    //分割线
    [self addSubview:[WYPublic getFenGexian:0 :(CGRectGetMinY(idLab.frame)-4)*AUTOY :WYMWITH :0.5]];
    CGFloat add = 4;
    [self addSubview:[WYPublic getFenGexian:0 :(CGRectGetMaxY(idLab.frame)+add)*AUTOY :WYMWITH :0.5]];
    [self addSubview:[WYPublic getFenGexian:0 :(CGRectGetMaxY(nameBtn.frame)+add)*AUTOY :WYMWITH :0.5]];
    [self addSubview:[WYPublic getFenGexian:0 :(CGRectGetMaxY(phoneLab.frame)+add)*AUTOY :WYMWITH :0.5]];
    [self addSubview:[WYPublic getFenGexian:0 :(CGRectGetMaxY(sexBtn.frame)+add)*AUTOY :WYMWITH :0.5]];
    [self addSubview:[WYPublic getFenGexian:0 :(CGRectGetMaxY(ageBtn.frame)+add)*AUTOY :WYMWITH :0.5]];
    img.userInteractionEnabled = YES;
    UITapGestureRecognizer *portraitTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(editPortrait)];
    [img addGestureRecognizer:portraitTap];
}
//给window添加一个遮罩层
- (void)addZheZhao
{
    UIView *zheZhao = [[UIView alloc]initWithFrame:CGRectMake(0,0,WYMWITH, WYMHEIGHT)];
    zheZhao.tag = 1111;
    zheZhao.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.4];
    UIActivityIndicatorView *ac = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    ac.center = CGPointMake(WYMWITH/2, WYMHEIGHT/2);
    [ac startAnimating];
    
    [self.father.view addSubview:zheZhao];
}
//去掉window的遮罩
- (void)removeZheZhao
{
    UIView *zhezhao = [self.father.view viewWithTag:1111];
    [zhezhao removeFromSuperview];
}

//编辑昵称
- (IBAction)nicheng:(id)sender {
    [self addZheZhao];
    NameInPutView *nameV = [[[NSBundle mainBundle] loadNibNamed:@"NameInPutView" owner:self options:nil]lastObject];
    [nameV morenzhi:[nameBtn titleForState:UIControlStateNormal]];
    nameV.father =self;
    [self.father.view addSubview:nameV];
    nameV.frame = CGRectMake(WYMWITH/2 - nameV.frame.size.width/2, -1*nameV.frame.size.height, nameV.frame.size.width, nameV.frame.size.height);
    [UIView animateWithDuration:0.15 animations:^{
        nameV.center = CGPointMake(WYMWITH/2, WYMHEIGHT/2-100*AUTOY);
    }];
}
//编辑姓名
- (void)changeName:(NSString *)name
{
    [self removeZheZhao];
    [nameBtn setTitle:name forState:UIControlStateNormal];
}
//电话

//性别
- (IBAction)sexbtnOn:(id)sender {
    [self addZheZhao];
    SexInPutView *sexV = [[[NSBundle mainBundle] loadNibNamed:@"SexInPutView" owner:self options:nil]lastObject];
    [sexV morenzhi:[sexBtn titleForState:UIControlStateNormal]];
    sexV.father =self;
    [self.father.view addSubview:sexV];
    sexV.frame = CGRectMake(WYMWITH/2 - sexV.frame.size.width/2, -1*sexV.frame.size.height, sexV.frame.size.width, sexV.frame.size.height);
    [UIView animateWithDuration:0.15 animations:^{
        sexV.center = CGPointMake(WYMWITH/2, WYMHEIGHT/2-100*AUTOY);
    }];

}
//编辑性别
- (void)changeSex:(NSString *)sex
{
    [self removeZheZhao];
    [sexBtn setTitle:sex forState:UIControlStateNormal];
}
//编辑年龄
- (void)changeAge:(NSString *)age
{
    [self removeZheZhao];
    
    [ageBtn setTitle:age forState:UIControlStateNormal];
}

- (IBAction)imageBtnClick:(UIButton *)sender {
    
    [self editPortrait];
}
//年龄
- (IBAction)ageBtnOn:(id)sender {
    [self addZheZhao];
    AgeInPutView *ageV = [[[NSBundle mainBundle] loadNibNamed:@"AgeInPutView" owner:self options:nil]lastObject];
    ageV.father =self;
    [ageV morenzhi:[ageBtn titleForState:UIControlStateNormal]];
    [self.father.view addSubview:ageV];
    ageV.frame = CGRectMake(WYMWITH/2 - ageV.frame.size.width/2, -1*ageV.frame.size.height, ageV.frame.size.width, ageV.frame.size.height);
    [UIView animateWithDuration:0.15 animations:^{
        ageV.center = CGPointMake(WYMWITH/2, WYMHEIGHT/2-100*AUTOY);
    }];
}


//确定按钮
- (IBAction)ensureBtnOnClick:(id)sender {
//    [WYPublic showMessageWithTitle:@"hello" Msg:@"world" view:self completion:^{
//        NSLog(@"hello");
//    }];
//    return;
    [WYPublic addZheZhaoToWindowWithTitle:nil];
    NSString *sex = [sexBtn titleForState:UIControlStateNormal];
    int setindex = 0;
    if ([sex isEqualToString:@"男"]) {
        setindex = 1;
    }else if ([sex isEqualToString:@"保密"]){
        setindex = -1;
    }
    NSDictionary *params = @{@"username":[nameBtn titleForState:UIControlStateNormal],@"gender":[NSNumber numberWithInt:setindex],@"age":[ageBtn titleForState:UIControlStateNormal],@"uid":[UserInfo getUserID],@"token":[UserInfo getUserToken],@"refresh_token":[UserInfo getRefreshToken]};
    
    [WYRequest startPostForDicWithUrlStR:[NSString stringWithFormat:@"%@%@",DBB_IP,EDIT_INFO_URL] Parameters:params successBlock:^(NSDictionary *dic) {
        NSNumber *ret = dic[@"ret"];
        if (ret.intValue == 0) {
            [UserInfo updateUserInfoWithDic:dic[@"data"]];
            [WYPublic showMessageWithTitle:@"提示：" Msg:@"资料修改成功"];
        }else{
//            NSArray *allKeys = dic.allKeys;
            
            if (ret.intValue == 1004){
                [WYPublic showMessageWithTitle:@"提示" Msg:@"您的昵称,性别,年龄可能没有改变"];
            }
//            NSString *msg = dic[@"msg"];
//            
//            [WYPublic showMessageWithTitle:@"提示：" Msg:msg];
            
            if(ret.intValue>2000 && ret.intValue < 3000){
                //用户过期，强制重新登录 先删除用户信息
                [UserInfo deleteUserInfo];
                //登录
                [WYPublic ifUserHaveLogin];
            }
        }
        [WYPublic removeZheZhaoToWindow];
    } failedBlock:^{
        [WYPublic removeZheZhaoToWindow];
        [WYPublic showMessageWithTitle:@"提示：" Msg:@"资料修改失败"];
    } needLog:NO];
}


- (void)editPortrait {
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"拍照", @"从相册中选取", nil];
    [choiceSheet showInView:self.father.view];
}
/****************上传头像*****************/
- (void)uplodeUserImage {
    [WYPublic addZheZhaoToWindowWithTitle:nil];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    //设置请求头
    [manager.requestSerializer setValue:[WYRequest httpHeaderFieldString] forHTTPHeaderField:@"User-Agent"];

    NSDictionary *parameters =@{@"uid":[UserInfo getUserID],@"token":[UserInfo getUserToken],@"refresh_token":[UserInfo getRefreshToken]};
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0]; //path数组里貌似只有一个元素
    NSString *filestr = @"/1.jpg";
    NSString *newstr = [documentsDirectory stringByAppendingString:filestr];
//    NSData *dd = [NSData dataWithContentsOfFile:newstr];
    NSData *dd = [NSData dataWithContentsOfFile:self.selectedImageStr];

    // 加载头像
//    userImageSupView.image = [UIImage imageWithData:dd];
    
    [manager POST:[NSString stringWithFormat:@"%@%@",DBB_IP,POST_IMG_URL] parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:dd name:@"avatar" fileName:@"1.jpg" mimeType:@"image/jpeg"];
        
    } success:^(AFHTTPRequestOperation *operation,id responseObject) {
        [WYPublic removeZheZhaoToWindow];
        //请求成功的回调
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableContainers error:nil];
        NSNumber *ret = dic[@"ret"];
        if (ret.intValue == 0) {
            [WYPublic showMessageWithTitle:@"提示：" Msg:@"图片上传成功"];
            
        }else{
            [WYPublic showMessageWithTitle:@"提示：" Msg:@"图片上传失败"];
            if(ret.intValue>2000 && ret.intValue < 3000){
                //用户过期，强制重新登录 先删除用户信息
                [UserInfo deleteUserInfo];
                //登录
                [WYPublic ifUserHaveLogin];
            }
        }
    } failure:^(AFHTTPRequestOperation *operation,NSError *error) {
        [WYPublic removeZheZhaoToWindow];
    }];
    
}
#pragma mark VPImageCropperDelegate
- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    //完成赋值
    img.image = editedImage;
    // 把头像图片存到本地
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"1.jpg"]];   // 保存文件的名称
    NSData *imageData = UIImageJPEGRepresentation(editedImage, 0.5);
    [imageData writeToFile:filePath atomically:YES];
    self.selectedImageStr = filePath;
    //上传图像
    [self uplodeUserImage];
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
        // TO DO
    }];
}

- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
    [cropperViewController dismissViewControllerAnimated:NO completion:^{
    }];
}

#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        // 拍照
        if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypeCamera;
            if ([self isFrontCameraAvailable]) {
                controller.cameraDevice = UIImagePickerControllerCameraDeviceFront;
            }
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [self.father presentViewController:controller
                               animated:NO
                             completion:^(void){
                                 NSLog(@"Picker View Controller is presented");
                             }];
        }
        
    } else if (buttonIndex == 1) {
        // 从相册中选取
        if ([self isPhotoLibraryAvailable]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [self.father presentViewController:controller
                               animated:NO
                             completion:^(void){
                                 NSLog(@"Picker View Controller is presented");
                             }];
        }
    }
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^() {
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        portraitImg = [self imageByScalingToMaxSize:portraitImg];
        // 裁剪
        VPImageCropperViewController *imgEditorVC = [[VPImageCropperViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake(0, 100.0f, self.father.view.frame.size.width, self.father.view.frame.size.width) limitScaleRatio:3.0];
        imgEditorVC.delegate = self;
        [self.father presentViewController:imgEditorVC animated:NO completion:^{
            // TO DO
        }];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}

#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    
}

#pragma mark camera utility
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickVideosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}

#pragma mark image scale utility
- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < ORIGINAL_MAX_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = ORIGINAL_MAX_WIDTH;
        btWidth = sourceImage.size.width * (ORIGINAL_MAX_WIDTH / sourceImage.size.height);
    } else {
        btWidth = ORIGINAL_MAX_WIDTH;
        btHeight = sourceImage.size.height * (ORIGINAL_MAX_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
    

}


@end
